package com.pms.web;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.pms.entity.BaseGroupMember;
import com.pms.entity.BaseModel;
import com.pms.entity.BaseUser;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.rpc.ICompanyService;
import com.pms.rpc.IKyOrganizationRPCService;
import com.pms.rpc.IotGroupAgencyRpcService;
import com.pms.service.IBaseUserService;
import com.pms.util.idutil.SnowFlake;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import com.pms.controller.BaseController;
import com.pms.service.ICompanyCodeService;
import com.pms.entity.CompanyCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 系统编码
 */
@RestController
@RequestMapping("companyCode")
@Api(value = "系统编码管理",description = "系统编码管理")
public class CompanyCodeController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);
    @Autowired
    ICompanyCodeService companyCodeService;
    @Autowired
    IBaseUserService baseUserService;
    @Autowired
    ICompanyService iCompanyService;
    @Autowired
    IKyOrganizationRPCService iKyOrganizationRPCService;
    /**
     * 添加系统编码信息
     * @param companyName
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("添加系统编码信息")
    @ApiImplicitParams({
             @ApiImplicitParam(name="companyName",value="公司名称",required = true,dataType = "String",paramType="form"),
             @ApiImplicitParam(name="phone",value="公司联系号码",required = true,dataType = "String",paramType="form"),
             @ApiImplicitParam(name="name",value="联系人姓名",required = true,dataType = "String",paramType="form"),
             @ApiImplicitParam(name="detail",value="简介",required = true,dataType = "String",paramType="form"),
             @ApiImplicitParam(name="type",value="公司代码生成方式(1系统生成2.自定义)",required = true,dataType = "int",paramType="form"),
             @ApiImplicitParam(name="companyCode",value="系统编码",required = false,dataType = "String",paramType="form"),
           })
    public R add(String companyName,String phone,String name,String detail,int type,String companyCode ){
        parameterIsNull(companyName,"请填写公司名称");
        parameterIsNull(phone,"请填写公司联系号码");
        parameterIsNull(name,"请填写联系人姓名");
        parameterIsNull(detail,"请填写简介");
        parameterIsNull(type,"请填写公司代码生成方式");
        CompanyCode CompanyName= companyCodeService.selectOne(new EntityWrapper<CompanyCode>().eq("company_name",companyName));
       if (CompanyName!=null){return R.error("该公司名称信息已存在，请从新输入！");}
        //添加系统编码信息
        CompanyCode entity=new CompanyCode();
        entity.setType(type);
           if (type==1){//系统生成
               entity.setCompanyCode(companyCodeService.getInviteCode(6));//生成了6位系统编码
           }else if (type==2){//自定义
               parameterIsNull(companyCode,"请填写系统编码");
               if(companyCode.length()!=6){return R.error("系统编码只能为6位数");}
               CompanyCode code= companyCodeService.selectOne(new EntityWrapper<CompanyCode>().eq("company_code",companyCode));
               if (code!=null){return R.error("已有相同公司代码，请重新输入");}
               entity.setCompanyCode(companyCode);
           }
        Long id= BaseModel.returnStaticIdLong();
        entity.setId(id);
        entity.setName(name);
        entity.setDetail(detail);
        entity.setStatus(1);
        entity.setCrtTime(new Date());
        entity.setPhone(phone);
        entity.setCompanyName(companyName);
        //添加管理员
        BaseUser user=new BaseUser();
        Long userId= BaseModel.returnStaticIdLong();
        user.setId(userId);//ID
        user.setCompanyCode(entity.getCompanyCode());//公司编码
        user.setPassword(BCrypt.hashpw("e10adc3949ba59abbe56e057f20f883e","$2a$12$S/yLlj9kzi5Dgsz97H4rAe9RZTx2QMcnckioqofjv8tYtoQKET/YG"));
        user.setUsername("admin");//账号
        user.setType(1);//类型
        user.setMobilePhone(phone);
        user.setName(entity.getCompanyName()+"管理员");//昵称
        user.setEmail(null);
        user.setCrtTime(new Date());
        user.setImg("http://upimg.ahmkj.cn/pms/img82389271.jpg");
        user.setType(1);
        user.setCrtName(getCurrentUserMap().get("X_Name"));
        user.setStatus(1);//
        user.setSex(3);
        user.setDescription(entity.getCompanyName()+"管理员");
        //添加管理员角色绑定
        BaseGroupMember groupMember=new BaseGroupMember();
        groupMember.setUserId(userId.toString());
        groupMember.setGroupId("1");
        groupMember.setCrtTime(new Date());
        companyCodeService.insert_user_groupMember(entity,user,groupMember);
        return  R.ok();
    }

    /**
     * 修改
     * @param id
     * @param companyName
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("修改系统编码信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="系统编码ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="companyName",value="公司名称",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="phone",value="公司联系号码",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="name",value="联系人姓名",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="detail",value="简介",required = false,dataType = "String",paramType="form"),
    })
    public R update(Long id,String companyName,String phone,String name,String detail){
        parameterIsNull(id,"请填写公司ID");
        CompanyCode code=companyCodeService.selectById(id);
        if (code == null){return R.error("该公司名称信息不存在，请从新输入！");}
        if (StringUtils.isNotBlank(companyName)){
            if (!companyName.equals(code.getCompanyName())){
                CompanyCode codename= companyCodeService.selectOne(new EntityWrapper<CompanyCode>().eq("company_name",companyName));
                if (codename!=null){return R.error("该公司名称信息已存在，请从新输入！");}
                code.setCompanyName(companyName);
                iKyOrganizationRPCService.updateByCode(code.getCompanyCode(),companyName);
            }
        }
        if (StringUtils.isNotBlank(phone)){
           code.setPhone(phone);
        }
        if (StringUtils.isNotBlank(name)){
            code.setName(name);
        }
        if (StringUtils.isNotBlank(detail)){
            code.setDetail(detail);
        }
        code.setUpdTime(new Date());
        companyCodeService.updateById(code);
        return R.ok();
    }

    /**
     * 修改
     * @param id
     * @param status
     * @return
     */
    @PostMapping("/updateByStatus")
    @ApiOperation("修改状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="系统编码ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="status",value="1启用2禁用",required = true,dataType = "Integer",paramType="form"),
    })
    public R updateByStatus(Long id,Integer status){
        parameterIsNull(id,"请填写公司ID");
        parameterIsNull(status,"请填写状态");
        CompanyCode code=companyCodeService.selectById(id);
        if (code == null){return R.error("该公司名称信息不存在，请从新输入！");}
        if (status!=null){
            code.setStatus(status);
        }
        companyCodeService.updateById(code);
        return R.ok();
    }

    /**
     * 查询单条系统编码信息
     * @param id
     * @returnm/,
     */
    @PostMapping("/findById")
    @ApiOperation("查询单条系统编码信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="系统编码ID",required = true,dataType = "Long",paramType="form"),
          })
    public R findById(Long id){
        parameterIsNull(id,"请填写公司ID");
        CompanyCode   companyCode=companyCodeService.selectById(id);
        return R.ok().put("data",companyCode);
    }

    /**
     * 分页查询系统编码信息
     * @param limit
     * @param page
     * @param name
     * @return
     */
    @PostMapping(value = "/page")
    @ApiOperation("分页查询系统编码信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "limit", value = "条数", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "name", value = "", required = false, dataType = "String", paramType = "form"),
           })
    public R page(int limit,int page, String name){
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        Page<CompanyCode> pages = new Page<>(page,limit);
        Map<String,Object> map =new HashMap<>();
        if (StringUtils.isNotBlank(name)){
            map.put("companyName","WHERE  company_name like  binary '%"+name+"%'");
        }
        map.put("limit",limit);
        map.put("page",(page-1)*limit);
        Page<CompanyCode> pageList = companyCodeService.selectBypageMap(pages,map);
        return  R.ok().put("data",pageList);
    }

    /**
     * 查询所有
     * @return
     */
    @PostMapping("/all")
    @ApiOperation("查询所有公司")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "", required = false, dataType = "String", paramType = "form"),
    })
    public List<CompanyCode> all(String name){
        Wrapper<CompanyCode> ew = new EntityWrapper<>();
        List<CompanyCode>  code=new ArrayList<>();
            if (StringUtils.isNotBlank(name)){
                ew.like("company_name",name);
                 code= companyCodeService.selectList(ew);
            }else {
                 code = companyCodeService.selectList(null);
            }
        return code;
    }

    /**
     * 根据公司查询用户
     * @param limit
     * @param page
     * @param companyCode
     * @param name
     * @param userStatus
     * @param groupType
     * @return
     */
    @PostMapping("/getCompanyCodeByUser")
    @ApiOperation("根据公司查询用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name="companyCode",value="系统编码",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="limit",value="条数",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="page",value="页数",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="name",value="",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="userStatus",value="用户状态（1启用2禁用3删除）",required = false,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="groupType",value="角色类型(1超级管理员2管理员3编辑者4浏览者5自定义)",required = false,dataType = "Integer",paramType="form"),
    })
    public R getCompanyCodeByUser(int limit,int page,String companyCode,String name,
                                  Integer userStatus, Integer groupType ){
        parameterIsNull(companyCode,"请填写系统编码");
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        Page<Map<String,Object>> pages = new Page<>(page,limit);
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("companyCode",companyCode);
        if (userStatus!=null){
            parameter.put("status","AND u.status = "+userStatus+"");
        }
        if (userStatus!=null && userStatus == 3){//查询删除数据
            parameter.put("status","AND u.deleted_state = 2");
        }
        if (groupType!=null){
            parameter.put("groupType","AND g.group_type = "+groupType+"");
        }
        if (StringUtils.isNotBlank(name)){
            parameter.put("name","and (u.username like binary '%"+name+"%' or g.name like binary '%"+name+"%'" +
                    "or u.crt_user like binary '%"+name+"%'or u.crt_name like binary '%"+name+"%'or u.crt_time like binary '%"+name+"%')");
        }
        parameter.put("limit",limit);
        parameter.put("page",(page-1)*limit);
        pages = baseUserService.selectPageCompanyCodeByUser(pages,parameter);
        return R.ok().put("data",pages);
    }

    /**
     * 删除系统
     * @param id
     * @return
     */
    @PostMapping("/deleteById")
    @ApiOperation("删除系统")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="系统编码ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="username",value="账号",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="password",value="密码",required = true,dataType = "String",paramType="form"),
    })
    public R deleteById(Long id,String username,String password){
        parameterIsNull(id,"请填写公司ID");
        parameterIsNull(username,"请输入账号");
        parameterIsNull(password,"请输入密码");
        CompanyCode code=companyCodeService.selectById(id);
        if (code == null){return R.error("该公司名称信息不存在，请从新输入！");}
        BaseUser user=baseUserService.getBySuperUser(username);
        if (null==user){ throw  new RRException("账号信息不存在",400);}
        if (2==user.getStatus()){ throw  new RRException("该账号已被停用，请联系管理员",400);}
        if (21!=user.getType()){ throw  new RRException("该账号不属于超级管理员，请从新输入",400);}
        if(encoder.matches(password,user.getPassword())){
            Integer state=iCompanyService.cleanUpCompanyData(code.getCompanyCode());
            if(!state.equals("-1")){
                iKyOrganizationRPCService.deleteSystemDataByCode(code.getCompanyCode());
                baseUserService.delete(new EntityWrapper<BaseUser>().eq("company_code",code.getCompanyCode()));
                companyCodeService.deleteById(code);
                return R.ok();
            }else {
                throw  new RRException("二汞删除数据异常",400);
            }

        }else {
            throw  new RRException("账号密码错误",400);
        }
    }

}